package com.websuites.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import com.websuites.core.exception.WsRuntimeException;
import com.websuites.core.persistence.PersistenceBean;

@SuppressWarnings("unchecked")
public class MybatisDaoImpl implements MybatisDao {

	private String defaultDataSource = "defaultDataSource";
	private Map sqlSessions;
	
	public String getDefaultDataSource() {
		return defaultDataSource;
	}

	public void setDefaultDataSource(String defaultDataSource) {
		this.defaultDataSource = defaultDataSource;
	}

	public void setSqlSessions(Map sqlSessions) {
		this.sqlSessions = sqlSessions;
	}
	
	public SqlSession getSqlSession(String sDataSource){
		if(sDataSource==null || sDataSource.trim().length()==0){
			if(defaultDataSource!=null && defaultDataSource.trim().length()>0){
				sDataSource = defaultDataSource;
			}
			else{
				throw new WsRuntimeException("datasource is null");
			}
		}	
		return (SqlSession)sqlSessions.get(sDataSource);
	}

	public List queryMyBatisList(String sDataSource, String sSqlID, Object o)
	{
		if(dispatchDataSource(sDataSource)){
			return getSqlSession(sDataSource).selectList(sSqlID, o);
		}
		return getSqlSession(null).selectList(sSqlID, o);
	}

	public Object queryMyBatisObject(String sDataSource, String sSqlID, Object o)
	{ 
		if(dispatchDataSource(sDataSource)){
			return getSqlSession(sDataSource).selectOne(sSqlID, o);
		}
		return getSqlSession(null).selectOne(sSqlID, o);
	}

	public int updateMyBatis(String sDataSource, String sSqlID, Object o)
	{
		if(dispatchDataSource(sDataSource)){
			return getSqlSession(sDataSource).update(sSqlID, o);
		}
		return getSqlSession(null).update(sSqlID, o);
	}

	public int deleteMyBatis(String sDataSource, String sSqlID, Object o)
	{
		if(dispatchDataSource(sDataSource)){
			return getSqlSession(sDataSource).delete(sSqlID, o);
		}
		return getSqlSession(null).delete(sSqlID, o);		
	}

	public int insertMyBatis(String sDataSource, String sSqlID, Object o)
	{
		if(dispatchDataSource(sDataSource)){
			return getSqlSession(sDataSource).insert(sSqlID, o);
		}
		return getSqlSession(null).insert(sSqlID, o);
	}
	
	private boolean dispatchDataSource(String sDataSource){
		return (sDataSource!=null && sDataSource.trim().length()>0);
	}

	@Override
	public List query(String sSql, Object o, PersistenceBean entry) {
		return queryMyBatisList(entry.getDataSource(), sSql, o);
	}

	@Override
	public int insert(String sSql, Object o, PersistenceBean entry) {	
		return insertMyBatis(entry.getDataSource(), sSql, o);
	}

	@Override
	public int delete(String sSql, Object o, PersistenceBean entry) {
		return deleteMyBatis(entry.getDataSource(), sSql, o);
	}

	@Override
	public int update(String sSql, Object o, PersistenceBean entry) {
		return updateMyBatis(entry.getDataSource(), sSql, o);
	}
}
